import wx
import wx.html
import os
from analysePar import InformIncaParamWin
from app_analysevar.checkfile import CheckFileWin
from compareA2l import CompareA2lWin
from config import __VERSION__
import sys

class A2lAnalyse:
    def __init__(self):
        self.app = wx.App(redirect=False)
        self.app.SetOutputWindowAttributes('StdError', size=(700, 500))
        self.gui = MainFrame(mainobj=self, 
                             title='A2lAnalyse V' + '.'.join(map(str, __VERSION__)))  # 主框架
        self.app.SetTopWindow(self.gui)
        self.checkfile = None
        self.stdout = []

    def set_stdout(self,x):
        self.stdout.append(x)
        sys.stdout = x

    def unset_stdout(self, x):
        l=self.stdout
        for i,m in enumerate(l):
            if m is x:
                self.stdout.pop(i)
                break
        if len(self.stdout) > 0:
            sys.stdout = self.stdout[-1]
        else:
            sys.stdout = sys.__stdout__

########################################## GUI #####################################################
class MainFrame(wx.Frame):
    def __init__(self, mainobj, title):
        wx.Frame.__init__(self, None, title=title, size=(300, 300))
        # self.SetSize(wx.GetClientDisplayRect())  # 显示器工作区尺寸(除开任务栏)
        self.SetBackgroundColour(wx.Colour(83, 134, 139))
        # self.Centre()
        # self.Maximize()
        self.mainobj = mainobj

        self.pl = wx.Panel(self, size=(400, 600))
        self.bt = {}
        self.bt['anaparam'] = wx.Button(parent=self.pl, size=(100, 80), label='分析变量')
        self.bt['comparea2l'] = wx.Button(parent=self.pl, size=(100, 80), label='比对A2L')
        self.bt['checkfile'] = wx.Button(parent=self.pl, size=(100, 80), label='检查文件')

        self.sizer = wx.GridBagSizer(10, 10)
        self.sizer.Add(self.bt['anaparam'], pos=(0, 0), span=(1, 1), flag=wx.ALL, border=10)
        self.sizer.Add(self.bt['comparea2l'], pos=(0, 1), span=(1, 1), flag=wx.ALL, border=10)
        self.sizer.Add(self.bt['checkfile'], pos=(1, 0), span=(1, 1), flag=wx.ALL, border=10)

        self.pl.SetSizer(self.sizer)

        self.Bind(wx.EVT_BUTTON, lambda e: InformIncaParamWin(self, self.mainobj), self.bt['anaparam'])
        self.Bind(wx.EVT_BUTTON, lambda e: CompareA2lWin(self, self.mainobj), self.bt['comparea2l'])
        self.Bind(wx.EVT_BUTTON, lambda e: CheckFileWin(self, self.mainobj), self.bt['checkfile'])

        self.Centre()
        self.Show()

    def showhtml(self, html, mode='', **inform):
        HtmlWin(parent=self, mainobj=self.mainobj, text=html, mode=mode, **inform)


class HtmlWin(wx.Frame):
    """HTML窗口"""

    def __init__(self, parent=None, title='HtmlWin', mainobj=None, text='', mode='', **inform):
        wx.Frame.__init__(self, parent=parent, title=title, size=(1300, 700))
        self.mainobj = mainobj

        self.html = wx.html.HtmlWindow(self)
        self.toolbar = wx.ToolBar(self)
        self.sourse = text
        self.mode = mode
        self.inform = inform

        self.SetToolBar(self.toolbar)
        self.tooldic = {}
        self.tooldic['保存'] = self.toolbar.AddTool(0, 'a', IMGFolder.GetBitmap(),
                                                  shortHelp='保存到文件', kind=wx.ITEM_NORMAL)
        self.toolbar.Realize()

        self.html.SetPage(text)
        self.html.SetStandardFonts(14, '黑体')
        self.Bind(wx.EVT_TOOL, self.on_save, self.tooldic['保存'])

        self.Centre()
        # self.Layout()
        self.Show()

    def on_save(self, event):
        filetype = 'html文件(*.html)|*.html'
        default = '变量信息.html'
        while True:
            path = wx.SaveFileSelector('', filetype, default)
            if path and os.path.exists(path):
                affirm = wx.MessageBox('名称重复,确认要覆盖"%s"吗 ?? ' % os.path.basename(path), style=wx.YES_NO)
                if affirm == wx.YES:
                    break
            else:
                break
        if path:
            with open(path, 'w', encoding='utf-8') as f:
                f.write(self.sourse)
            wx.LogMessage('保存成功')


########################################## IMG ##################################################
from wx.lib.embeddedimage import PyEmbeddedImage

IMGFolder = PyEmbeddedImage('iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAq0lEQVQ4T+3UPQ5BQRQG0KOxCDag1apsQKliFQq'
                            'rUNgErRWoJQpLoBCNjkQjhDwhET/vTuKVpr1fTr7cmUxJwadUsOcPqmDztNcZmjim7vp1h6/gBUP0igIj5+1Svz'
                            'VsYRFp9/kJ20f2E7jGAP1EcIxOHji9D2sJ4BkNzCMwBcuMJerY54ErlBPaZZEJ2sia3k70bCK3i9Fz6BdwhyoOeW'
                            'DUKJz/f5twRWHgCqDyHBU+4MpMAAAAAElFTkSuQmCC')

##### Run ####
if __name__ == '__main__':
    obj = A2lAnalyse()
    obj.app.MainLoop()
